package com.fanghaoran.notes.filter;

import com.alibaba.fastjson.JSON;
import com.fanghaoran.notes.bean.MyResult;
import com.fanghaoran.notes.util.Constants;
import com.fanghaoran.notes.util.JdbcUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author: win11
 * @Date: 2023/05/03/11:37
 * @Description: 事务性过滤器
 */
public class TransactionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Connection connection=null;
        try {
            connection = JdbcUtil.getConnection();
            //开启事务
            connection.setAutoCommit(false);

            //执行事务
            chain.doFilter(request, response);

            //提交事务
            connection.commit();
        } catch (SQLException e) {
            System.out.println(connection != null);
            //回滚事务
            if (connection != null) {
                try {
                    connection.rollback();
                    e.printStackTrace();
                    System.out.println("rollback后");
                    response.getWriter().println(JSON.toJSONString(new MyResult(Constants.FAIL,null)));
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        } finally {
            //释放连接资源
            if (connection != null) {
                try {
                    JdbcUtil.freeConnection();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
